package leetcode.median;

import javax.swing.plaf.basic.BasicIconFactory;

/**
 * 最长回文子串
 */
public class $05_LongestPalindrome {

    public String longestPalindrome(String s) {
        int len = s.length();
        if (len < 2) {
            return s;
        }
        int maxLen = 1;
        int begin = 0;
        boolean[][] dp = new boolean[len][len];
        for (int i = 0;i < len;i++) {
            dp[i][i] = true;
        }
        char[] arr = s.toCharArray();
        for (int subLen = 2; subLen <= len;subLen++) {
            for (int i = 0;i < len;i++) {
                int j = subLen + i - 1;
                if (j >= len) {
                    break;
                }
                if (arr[i] != arr[j]) {
                    dp[i][j] = false;
                } else {
                    if (j - i < 3) {
                        dp[i][j] = true;
                    } else {
                        dp[i][j] = dp[i + 1][j - 1];
                    }
                }

                if (dp[i][j] && j - i + 1 > maxLen) {
                    maxLen = j - i + 1;
                    begin = i;
                }
            }
        }
        return s.substring(begin, begin + maxLen);
    }

    public String longestPalindrome2(String s) {
        int len = s.length();
        if (len < 2) {
            return s;
        }
        int maxLen = 0;
        String res = "";
        for (int center = 0; center <= 2 * len - 1;center++) {
            int left = center / 2;
            int right = left + center % 2;
            while (left >= 0 && right < len && s.charAt(left) == s.charAt(right)) {
                int curLen = right - left + 1;
                if (curLen > maxLen) {
                    maxLen  = curLen;
                    res = s.substring(left, right + 1);
                }
                left--;
                right++;
            }
        }
        return res;
    }

}
